<?php

namespace App\Admin\Controllers;

use Carbon\Carbon;
use App\Models\Order;
use Encore\Admin\Grid;
use App\Exports\OrderExport;
use App\Jobs\OrderImportJob;
use Encore\Admin\Layout\Content;
use App\Supports\Delivery\Express;
use Illuminate\Support\Facades\DB;
use App\Events\OrderDeliveredEvent;
use App\Admin\Tools\OrderImportTool;
use App\Admin\Tools\OrderExportTool;
use Illuminate\Support\Facades\Storage;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\OrderAction\OrderCancel;
use Illuminate\Foundation\Validation\ValidatesRequests;

class OrdersController extends AdminController
{
	use ValidatesRequests;

    protected $title = '订单管理';

    protected function grid()
    {
        $grid = new Grid(new Order());
	    $grid->model()->orderByDesc('id');

	    if ($userId = request('user_id')) {
		    $grid->model()->where('user_id', $userId)->orderByDesc('id');
	    }

	    $grid->column('id', 'ID')->width(80);
	    $grid->column('user_id', '会员')->display(function () {
	    	return $this->user ? $this->user->nameText(true) : '';
	    });
	    $grid->column('number', '订单号')->display(function ($value) {
            if ($this->gold_waste_id) {
                $diliveryAt = $this->user->gold_wastes_order_at->toDateString();
                return "{$value}<br>发货时间：<b style='color: #0073ff'>{$diliveryAt}</b>";
            }
            return "{$value}<br>发货时间：正常发货";
        });

	    $grid->column('created_at', '下单时间')->display(function () {
		    return (string)$this->created_at;
	    });
	    $grid->column('paid_at', '付款时间')->display(function () {
		    return $this->paid_at ? (string)$this->paid_at : '待付款...';
	    });
	    $grid->column('paid_method', '付款方式')->display(function ($value) {
	    	if (empty($value) and empty($this->paid_at)) {
	    		return "<i class='fa fa-times-circle text-default'></i> 未支付";
	    	}
	    	if (empty($value) and !empty($this->paid_at)) {
			    return "<i class='fa fa-check-circle text-success'></i> 黄金账户";
		    }
	    	$method = config("site.payment.methods.{$value}");
	    	$method = empty($method) ? $value : $method;
	    	$text = "<i class='fa fa-check-circle text-success'></i> {$method}";
		    return $text;
	    });
	    $grid->column('total_amount', '金额');
	    $grid->column('delivery_status', '物流状态')->display(function ($value) {
		    if ($value === 'pending' and $this->paid_at) {
		    	return _label('待发货', 'default');
		    }
		    if ($value === 'pending' and !$this->paid_at) {
		    	return _label('待付款', 'danger');
		    }
		    if ($value === 'pending') {
		    	return _label('待发货', 'default');
		    }
		    if ($value === 'delivered') {
		    	return _label('已发货', 'info');
		    }
		    if ($value === 'received') {
		    	return _label('已收货', 'primary');
		    }
		    return '';
	    });
	    $grid->column('closed_at', '关闭状态')->display(function ($value) {
		    return $value ? _label('超时关闭', 'default') : _label('状态正常', 'success');
	    });
	    $grid->column('cancelled_at', '取消状态')->display(function ($value) {
		    return empty($value) ? _label('状态正常', 'success') : _label('已经取消', 'danger');
	    });
	    $grid->column('has_refund', '售后状态')->display(function () {
	    	$refund = $this->refunds()->first();
	    	if ($refund) {
			    return _label(Order::$refundStatus[$refund->refund_status], 'primary');
		    }
	    	return '';
	    });

	    $this->gridFilter($grid);
	    $this->gridTools($grid);
	    $grid->disableRowSelector();
	    $grid->disableCreateButton();
	    $grid->disableExport();
	    $this->gridActions($grid);

        return $grid;
    }

	protected function gridFilter(Grid $grid)
	{
		$grid->filter(function (Grid\Filter $filter) {

			$filter->expand();

			$filter->scope('closed', '已关闭')->closed();
			$filter->scope('unpaid', '待付款')->unpaid();
			$filter->scope('undelivered', '待发货')->undelivered();
			$filter->scope('delivered', '已发货')->delivered();
			$filter->scope('received', '已收货')->received();
			$filter->scope('received', '已收货')->received();
			$filter->scope('wastes', '旧单提货')->where('gold_waste_id', '>', 0);

			$filter->column(1/2, function (Grid\Filter $filter) {
				$filter->disableIdFilter();
				$filter->equal('id', '订单ID');
			});

			$filter->column(1/2, function (Grid\Filter $filter) {
				$filter->endsWith('number', '订单号');
			});

		});
	}

    protected function gridTools(Grid $grid)
    {
    	$grid->tools(function (Grid\Tools $tools) {
		    $tools->append(new OrderExportTool());
		    $tools->append(new OrderImportTool());
	    });
    }

    protected function gridActions(Grid $grid)
    {
    	$grid->actions(function (Grid\Displayers\Actions $actions) {
    		$actions->disableEdit();
    		$actions->disableDelete();
    		$actions->add(new OrderCancel());
	    });
    }

    public function show($id, Content $content)
    {
    	$order = Order::findOrFail($id);
	    $express = app(Express::class)->track($order); 
	    return $content->header('订单明细')
		    ->body(view('admin.orders.show', [
			    'order' => $order, 'express' => $express,
		    ]));
    }

    public function exportNormal()
    {
    	if (Order::query()->undelivered()->doesntExist()) {
    		admin_toastr('无待发货订单', 'error');
    		return redirect()->back();
	    }
    	$time = Carbon::now()->toDateTimeString();
	    (new OrderExport())->queue("orders/export/{$time}-导出普通待发货订单.xlsx", 'oss')->allOnQueue('file');
	    admin_toastr('导出普通待发货订单已提交', 'success');
    	return redirect()->back();
    }

    public function exports(Content $content)
    {
    	$orders = Storage::files('orders/export');
    	rsort($orders);
    	foreach ($orders as $k => $v) {
    		if ($k >= 3) {
    			Storage::delete($v);
    			unset($orders[$k]);
		    }
	    }
	    return $content->header('订单导出记录')
		    ->body(view('admin.orders.exports', [
			    'orders' => $orders
		    ]));
    }

    public function deliver(Order $order)
    {
    	if (!$order->isPaid()) {
    		admin_error('title', '当前订单未支付');
    		return redirect()->back();
	    }

	    if ($order->isCancelled()) {
		    admin_error('title', '当前订单已取消');
		    return redirect()->back();
	    }

    	$data = $this->validate(request(), [
    		'delivery_company' => 'required',
		    'delivery_number' => 'required',
	    ], [], [
	    	'delivery_company' => '物流公司',
		    'delivery_number' => '物流单号',
	    ]);

    	$data['delivery_time'] = Carbon::now()->toDateTimeString();

    	DB::transaction(function () use ($order, $data) {
		    $order->items()->update([
			    'delivery_status' => 'delivered',
			    'delivery_data' => $data,
		    ]);

		    $order->update([
		    	'delivery_status' => 'delivered',
			    'delivery_data' => $data,
		    ]);
	    });

    	event(new OrderDeliveredEvent($order));

	    admin_toastr('发货成功', 'success');

    	return redirect()->back();
    }

	public function deliveries(Content $content)
	{
		return $content->header('订单批量发货')
			->body(view('admin.orders.deliveries'));
	}

	public function import()
	{
		$rows = request('rows');
		$rows = collect(explode("\r\n", $rows));

		if (empty($rows->first())) {
			admin_toastr('请按格式输入发货信息', 'error');
			return redirect()->back();
		}

		if ($rows->count() > 500) {
			admin_toastr('不可超过500条记录/次', 'error');
			return redirect()->back();
		}

		$fails = collect();

		foreach ($rows as $raw) {

			$tableRow = explode("\t", $raw);
			$spaceRow = explode(" ", $raw);

			$row = null;

			if (count($tableRow) == 4) {
				$row = $tableRow;
			} elseif (count($spaceRow) == 4) {
				$row = $spaceRow;
			}

			if (!$row) continue;

			if (!isset($row[0]) or !isset($row[1])
				or !isset($row[2]) or !isset($row[3])) {
				continue;
			}

			DB::transaction(function () use ($row, $fails) {

				$orderId = isset($row[0]) ? $row[0] : null;
				$orderNumber = isset($row[1]) ? $row[1] : null;
				$expressCode = isset($row[2]) ? express_code($row[2]) : null;
				$expressNumber = isset($row[3]) ? $row[3] : null;

				$order = Order::where('id', $orderId)->where('number', $orderNumber)->first();

				if ($expressCode and $expressNumber
					and $order and $order->isPaid()) {

					$deliveryData = [
						'delivery_company' => $expressCode,
						'delivery_number' => $expressNumber,
					];
					$order->update([
						'delivery_status' => 'delivered',
						'delivery_data' => $deliveryData,
					]);
					$order->items()->update([
						'delivery_status' => 'delivered',
						'delivery_data' => $deliveryData,
					]);
				} else {
					$fails->push($row);
				}
			});
		}

		session()->put('failed_deliveries', $fails);
		$failedCount = $fails->count();

		admin_toastr("发货提交(失败:{$failedCount})", 'success');

		return redirect()->back();
	}
}
